package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisherV2;
import com.alibaba.csp.sentinel.dashboard.util.ConverterUtils;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author tom
 */
public abstract class AbstractDynamicRulePublisher<T> implements DynamicRulePublisherV2<List<T>> {
    @Autowired
    private ConfigService configService;

    @Override
    public boolean publish(String app, List<T> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return false;
        }
        return configService.publishConfig(getDataId(app),
                getGroup(app), ConverterUtils.toJsonString(rules));
    }

    protected abstract String getDataId(String app);

    protected String getGroup(String app) {
        return app;
    }
}
